﻿/* 十六进制字符串类
 */

namespace LSLib.StringEx
{
    using System;
    using System.Collections.Generic;
    using System.Text;

    public class HexString
    {
        /// <summary>byte数组转换为十六进制字符串
        /// </summary>
        public static string Bytes2HexString(byte[] input)
        {
            if (input == null) throw new ArgumentNullException("input");

            StringBuilder result = new StringBuilder();
            for (int i = 0; i < input.Length; i++)
            {
                result.Append(input[i].ToString("X2"));
            }
            return result.ToString();
        }

        /// <summary>十六进制字符串转换为byte数组
        /// </summary>
        /// <param name="hexString">十六进制字符串</param>
        /// <returns>byte数组</returns>
        public static byte[] HexString2Bytes(string hexString)
        {
            if (hexString == null) throw new ArgumentNullException("hexString");
            if (hexString == string.Empty) return null;

            List<byte> result = new List<byte>();
            for (int i = 0; i < hexString.Length / 2; i++)
            {
                string stmpStr = hexString.Substring(i * 2, 2);
                byte oneByte;
                try
                {
                    oneByte = byte.Parse(stmpStr, System.Globalization.NumberStyles.HexNumber);
                }
                catch { throw new ArgumentException("参数 hexString 不是正确的十六进制字符串。", "hexString"); }
                result.Add(oneByte);
            }
            return result.ToArray();
        }
    }
}
